document.addEventListener('DOMContentLoaded', function() {
    const questionNav = document.querySelector(".question-nav")
    let mainContent = document.querySelector(".main-content")
    let d1 = document.createElement("div");
    let d2= document.createElement("div");
    let d3= document.createElement("div");
    let d4= document.createElement("div");
    let d5= document.createElement("div");
    mainContent.innerHTML='';
    // 标头
    $.ajax({
        url:"/exam/GetExamById",
        type:"post",
        data:{
            id:$.cookie("examId")
        },
        async:false,
        success: function(data){
            var obj = data.data;
            mainContent.innerHTML+=`
                <div class="paper-header">
                  <h1 class="paper-title">${obj.name}</h1>
                  <div class="paper-info">
                    <span class="creator">创建人：${obj.creator}</span>
                    <span class="duration">时间：${obj.duration}分钟</span>
                    <span class="totalScore">总分：${obj.totalScore}分</span>
                  </div>
                  <button class="back-button">
                        <i class="fas fa-arrow-left"></i>
                        <span>返回</span>
                  </button>
            `
        }
    })
    // 每个的数量
    $.ajax({
        url:"/question/getQuestionTypeAndCount",
        type:"post",
        data:{
            id:$.cookie("examId")
        },
        async:false,
        success: function(data){
            console.log(data.data)
            var arr = data.data
            questionNav.innerHTML = ""
            let count = 1;
            for(let i = 0;i < arr.length;i++){
                questionNav.innerHTML+=`
                      <div class="question-category">
                        <div class="category-title">
                          <span>${arr[i].type}</span>
                          <span>${arr[i].count}题</span>
                        </div>
                        <ul class="question-list" data-type="${arr[i].type}">
                        </ul>
                      </div>
                `
                if(arr[i].type == "选择题"){
                    d1.innerHTML+=`
                        <div class="question-container" id="choice-questions">
                          <h3 class="question-type">
                            <i class="fas fa-check-circle"></i> 一、选择题（每题${arr[i].score}分，共${arr[i].score*arr[i].count}分）
                          </h3>
                        </div>
                    `
                    // d1 = document.querySelector("#choice-questions")
                }else if(arr[i].type == "判断题"){
                    d2.innerHTML+=`
                        <div class="question-container" id="judge-questions">
                          <h3 class="question-type">
                            <i class="fas fa-balance-scale"></i> 二、判断题（每题${arr[i].score}分，共${arr[i].score*arr[i].count}分）
                          </h3>
                        </div>
                    `
                    // d2 = document.querySelector("#judge-questions")
                }else if(arr[i].type=="填空题"){
                    d3.innerHTML+=`
                        <div class="question-container" id="fill-questions">
                          <h3 class="question-type">
                            <i class="fas fa-pencil-alt"></i>三、填空题（每题${arr[i].score}分，共${arr[i].score*arr[i].count}分）
                          </h3>
                        </div>
                    `
                    // d3 = document.querySelector("#fill-questions")
                }else if(arr[i].type == "简答题"){
                    d4.innerHTML+=`
                        <div class="question-container" id="jianda-questions">
                          <h3 class="question-type">
                            <i class="fas fa-pencil-alt"></i> 四、简答题（每题${arr[i].score}分，共${arr[i].score*arr[i].count}分）
                          </h3>
                        </div>
                    `
                    // d4 = document.querySelector("#jianda-questions")
                }else if(arr[i].type == "计算题"){
                    d5.innerHTML+=`
                        <div class="question-container" id="calculate-questions">
                          <h3 class="question-type">
                            <i class="fas fa-calculator"></i> 五、计算题（每题${arr[i].score}分，共${arr[i].score*arr[i].count}分）
                          </h3>
                        </div>
                    `
                    // d5 = document.querySelector("#calculate-questions")
                }
                const questionLists = document.querySelector(`ul.question-list[data-type="${arr[i].type}"]`);
                for(let j = 0;j < arr[i].count;j++){
                    questionLists.innerHTML+=`
                            <li class="question-item ${count ==1?'current':null}" data-id="q${count}">${count++}</li>
                    `
                }
            }
        }
    })
    // 所有题目
    $.ajax({
        url: '/question/getByExamId',
        type: 'post',
        async:false,
        data:{
            id:$.cookie("examId")
        },
        success: function(data){
            var arr = data.data;
            console.log(d1)
            for(let i = 0;i<arr.length;i++){
                if(arr[i].type == "选择题"){
                    console.log("选择题")
                    d1.innerHTML+=`
                <div class="question-block" id="q${i+1}">
                    <div class="question-title">
                      <span>${i+1}. ${arr[i].content}</span>
                      <span style="margin-left: auto; color: #6c757d; font-size: 14px;">(2分)</span>
                    </div>
                    <ul class="options-list">
                      <li class="option-item">
                        <input type="radio" name="q${i+1}" id="q${i+1}-a" class="option-radio" value="A">
                        <label for="q${i+1}-a" class="option-label">A</label>
                        <div class="option-text">${arr[i].optionsList[0].split(". ")[1]}</div>
                      </li>
                      <li class="option-item">
                        <input type="radio" name="q${i+1}" id="q${i+1}-b" class="option-radio" value="B">
                        <label for="q${i+1}-b" class="option-label">B</label>
                        <div class="option-text">${arr[i].optionsList[1].split(". ")[1]}</div>
                      </li>
                      <li class="option-item">
                        <input type="radio" name="q${i+1}" id="q${i+1}-c" class="option-radio" value="C">
                        <label for="q${i+1}-c" class="option-label">C</label>
                        <div class="option-text">${arr[i].optionsList[2].split(". ")[1]}</div>
                      </li>
                      <li class="option-item">
                        <input type="radio" name="q${i+1}" id="q${i+1}-d" class="option-radio" value="D">
                        <label for="q${i+1}-d" class="option-label">D</label>
                        <div class="option-text">${arr[i].optionsList[3].split(". ")[1]}</div>
                      </li>
                    </ul>
                  </div>
                `
                }else if(arr[i].type == "判断题"){
                    d2.innerHTML+=`
                        <div class="question-block" id="q${i+1}">
                            <div class="question-title">
                              <span>${i+1}. ${arr[i].content}</span>
                              <span style="margin-left: auto; color: #6c757d; font-size: 14px;">(${arr[i].score}分)</span>
                            </div>
                            <div style="display: flex; gap: 15px; margin-top: 10px;">
                              <label style="display: flex; align-items: center; cursor: pointer;">
                                <input type="radio" name="q${i+1}" value="正确" style="margin-right: 5px;"> 正确
                              </label>
                              <label style="display: flex; align-items: center; cursor: pointer;">
                                <input type="radio" name="q${i+1}" value="错误" style="margin-right: 5px;"> 错误
                              </label>
                            </div>
                          </div>
                    `
                }else if(arr[i].type=="填空题"){
                    d3.innerHTML+=`
                      <div class="question-block" id="q${i+1}">
                        <div class="question-title">
                          <span>${i+1}. ${arr[i].content}</span>
                          <span style="margin-left: auto; color: #6c757d; font-size: 14px;">(${arr[i].score}分)</span>
                        </div>
                        <input type="text" class="answer-input" placeholder="请在此输入答案">
                      </div>
                    `
                }else if(arr[i].type == "简答题"){
                    d4.innerHTML+=`
                        <div class="question-block" id="q${i+1}" data-type="简答题">
                          <div class="question-title">
                            <span>${i+1}. ${arr[i].content}</span>
                            <span style="margin-left: auto; color: #6c757d; font-size: 14px;">(${arr[i].score}分)</span>
                          </div>
                          <!-- 简答题特有的答题区域 -->
                          <div class="essay-answer-area">
                            <textarea
                              class="answer-textarea"
                              placeholder="请在此输入解题过程（建议不少于100字）"
                              rows="6"
                            ></textarea>
                            <div class="word-count">已输入<span class="count">0</span>字</div>
                          </div>
                        </div>
                    `
                }else if(arr[i].type == "计算题"){
                    d5.innerHTML+=`
                           <div class="question-block" id="q${i+1}">
                            <div class="question-title">
                              <span>${i+1}. ${arr[i].content}</span>
                              <span style="margin-left: auto; color: #6c757d; font-size: 14px;">(${arr[i].score}分)</span>
                            </div>
                            <textarea class="answer-textarea" placeholder="请在此输入解题过程"></textarea>
                          </div>
                    `
                }
            }

            mainContent.innerHTML+=d1.innerHTML+d2.innerHTML+d3.innerHTML+d4.innerHTML+d5.innerHTML;
        }
    })
// 获取所有题目项和题目块
    const questionItems = document.querySelectorAll('.question-item');
    const questionBlocks = document.querySelectorAll('.question-block');
// 初始化当前题目
    let currentQuestion = 'q1';

// 更新导航项状态
    function updateNavStatus() {
        questionItems.forEach(item => {
            const questionId = item.getAttribute('data-id');

            // 移除所有状态类
            item.classList.remove('current', 'completed');

            // 设置当前题目样式
            if (questionId === currentQuestion) {
                item.classList.add('current');

                // 自动滚动导航项到可视区域
                const navItem = document.querySelector(`.question-item[data-id="${questionId}"]`);
                if (navItem) {
                    const navItemTop = navItem.offsetTop;
                    const navHeight = questionNav.clientHeight;
                    const itemHeight = navItem.clientHeight;

                    // 计算滚动位置，使当前题目在导航中间位置
                    const scrollTo = navItemTop - (navHeight / 2) + (itemHeight / 2);
                    questionNav.scrollTo({
                        top: scrollTo,
                        behavior: 'smooth'
                    });
                }
            }
            // 设置已完成题目样式
            else if (isQuestionCompleted(questionId)) {
                item.classList.add('completed');
            }
        });
    }

// 检查题目是否已完成
    function isQuestionCompleted(questionId) {
        const questionBlock = document.getElementById(questionId);

        // 选择题和判断题
        const selectedRadio = questionBlock.querySelector('input[type="radio"]:checked');
        if (selectedRadio) return true;

        // 填空题
        const textInput = questionBlock.querySelector('.answer-input');
        if (textInput && textInput.value.trim() !== '') return true;

        // 计算题
        const textarea = questionBlock.querySelector('.answer-textarea');
        if (textarea && textarea.value.trim() !== '') return true;

        return false;
    }

// 题目导航点击事件
    questionItems.forEach(item => {
        item.addEventListener('click', function() {
            const questionId = this.getAttribute('data-id');
            currentQuestion = questionId;

            // 滚动到题目位置
            document.getElementById(questionId).scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });

            // 更新导航状态
            updateNavStatus();
        });
    });

// 为所有输入元素添加事件监听，用于检测答题状态变化
    document.querySelectorAll('input, textarea').forEach(input => {
        input.addEventListener('change', updateNavStatus);
        input.addEventListener('input', updateNavStatus);
    });

// 监听滚动事件，更新当前题目
    mainContent.addEventListener('scroll', function() {
        const scrollPosition = this.scrollTop + 100; // 加上偏移量

        questionBlocks.forEach(block => {
            const blockTop = block.offsetTop;
            const blockHeight = block.offsetHeight;

            if (scrollPosition >= blockTop && scrollPosition < blockTop + blockHeight) {
                const questionId = block.id;
                if (currentQuestion !== questionId) {
                    currentQuestion = questionId;
                    updateNavStatus();
                }
            }
        });
// 获取当前题目和容器元素
        const current = document.querySelector('.current');
        const container = document.querySelector('.container'); // 确保这是正确的滚动容器

        if (current) {
            // 使用更智能的滚动方式
            current.scrollIntoView({
                behavior: 'smooth',
                block: 'nearest', // 更自然的滚动行为
                inline: 'start'
            });

            // 如果需要额外的位置微调
            const containerHeight = container.clientHeight;
            const currentRect = current.getBoundingClientRect();
            const currentPosition = currentRect.top + container.scrollTop;

            // 检查是否需要额外调整
            const threshold = 100; // 调整阈值
            const scrollMargin = 20; // 滚动边距

            if (currentRect.top < threshold) {
                // 当前元素太靠近顶部，向下滚动
                container.scrollTo({
                    top: currentPosition - scrollMargin,
                    behavior: 'smooth'
                });
            } else if (currentRect.bottom > containerHeight - threshold) {
                // 当前元素太靠近底部，向上滚动
                container.scrollTo({
                    top: currentPosition - containerHeight + currentRect.height + scrollMargin,
                    behavior: 'smooth'
                });
            }
        }
    });
    $(".back-button").on("click",function (){
        location.href="ExamManagement"
    })
// 初始化导航状态
    updateNavStatus();
});

